'use strict';
import React from "react";
import {
    View,
    Image,
    Text,
    TouchableOpacity,
    StyleSheet,
    Dimensions,
    Animated,
    ActivityIndicator,
    InteractionManager
} from "react-native";
import Foreground from "../Components/Foreground";
import ParallaxScrollView from "react-native-parallax-scroll-view";
import FixedHeader from "../Components/FixedHeader";
import CommentStarView from "../Components/CommentStarView";
import FarmHouseSell from "./FarmHouseSell";
import WatchMapView from "../Components/WatchMapView";
import InitiatedHelpToBuy from "./InitiatedHelpToBuy";
import {_renderStar} from "../Utils/ViewUtils";
import IntroduceView from "../Components/IntroduceView";
import ViewPager from "react-native-viewpager";
import BottomShareView from "../Components/BottomShareView";
import BottomCommentBtn from "../Components/BottomCommentBtn";
import SomethingItemView from "../Components/SomethingItemView";
import ImageViewer from "./ImageViewer";
import RuralLibraryAPIService from "../Commom/RuralLibraryAPIService";
import Global from "../Commom/GlobalConst";
import Toast from "../Utils/toast";
let width = Dimensions.get('window').width;
import RegisteredContainer from '../Containers/RegisteredContainer';
const styles = StyleSheet.create({
    star: {
        width: 20,
        height: 20,
        marginRight: 5
    },
    btnBox: {
        marginRight: 5,
        borderRadius: 5,
        backgroundColor: '#38D68B',
        width: 60,
        height: 30,
        alignItems: 'center',
        justifyContent: 'center',
    },
    button: {
        color: 'white',
    },
    flexRow: {
        flexDirection: 'row',
        padding: 15,
        alignItems: 'center',
        borderTopWidth: 1,
        borderTopColor: '#F2F3F5'
    },
    tenBorderLine: {
        borderTopWidth: 15,
        borderTopColor: '#F2F3F5',
    },
    avatar: {
        width: 40,
        height: 40,
        marginRight: 5,
    },
    name: {
        flex: 1,
    },
    date: {
        textAlign: 'right',
        color: 'black',
    },
    rowContent: {
        flexDirection: 'row',
        alignItems: 'center',
        width: window.width - 10,
    },
    borderStyles: {
        borderTopWidth: 15,
        borderColor: '#F2F3F5',
    },
    somethingStyle: {
        flexDirection: 'row',
        padding: 15,
        paddingBottom: 5,
        alignItems: 'center',
    },
});


/**
 * 特产详情
 */
class SpecialtyDetailsPage extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            commentList: [],
            visible: true,
            dataSource: new ViewPager.DataSource({
                pageHasChanged: (p1, p2) => p1 !== p2,
            }),
            paddingBottom: new Animated.Value(0),
            SpecialtyDetails: {},
            images: [],
            phone: null,
            foods: [],
            is_collect: 0,
        };
    }

    viewPagerItemClick() {
        this.props.navigator.push({
            name: 'ImageViewer',
            component: ImageViewer,
            passProps: {
                source: this.state.images
            }
        })
    }

    goToSellPage() {
        this.props.navigator.push({
            name: 'FarmHouseSell',
            component: FarmHouseSell,
            passProps: {
                ID: this.state.SpecialtyDetails.pid,
            }
        });
    }

    goToHelpBuyPage() {
        if (Global.Const.token == '') {
            // Toast.show('请先登录！');
            this.props.navigator.push({
                id: 'RegisteredContainer',
                component: RegisteredContainer,
                passProps: {},
            });
            return;
        }
        this.props.navigator.push({
            name: 'InitiatedHelpToBuy',
            component: InitiatedHelpToBuy,
            passProps: {
                type: 1,
                image: this.state.images[0],
                title: this.state.SpecialtyDetails.title,
                id: this.props.ID,
            }
        })
    }

    componentDidMount() {
        let id = this.props.ID;
        InteractionManager.runAfterInteractions(() => {
            RuralLibraryAPIService.specialtyDetails(Global.Const.token, Global.Const.registeredId, id).then((ret)=> {
                this.setState({
                    SpecialtyDetails: ret,
                    commentList: ret.comment_list,
                    visible: false,
                    nearFoods: ret.near_foods,
                    foods: ret.near_foods,
                    images: ret.images,
                    phone: ret.phone,
                    is_collect: ret.is_collect,
                    dataSource: this.state.dataSource.cloneWithPages(ret.images),
                });
            }).catch((err)=> {
            });
        });
    }

    refreshComments() {
        console.log('refreshComments');
        let id = this.props.ID;
        RuralLibraryAPIService.specialtyDetails(Global.Const.token, Global.Const.registeredId, id).then((ret)=> {
            this.setState({
                commentList: ret.comment_list,
            });
        }).catch((err)=> {
        });
    }

    _renderViewPager() {
        return (
            <View style={{height: 245,width,}}>
                {this.state.images.length > 1 ? < ViewPager
                    locked={false}
                    isLoop={true}
                    autoPlay={true}
                    renderPageIndicator={false}
                    renderPage={(page)=>{
                        return (
                            <TouchableOpacity onPress={() => this.viewPagerItemClick()}>
                                <Image source={{uri:page}}
                                       style={{
                                                   height: 245,
                                                   width,
                                               }}
                                />
                            </TouchableOpacity>
            )
        }
    }
                    dataSource={this.state.dataSource
    }
                /> :
                    <TouchableOpacity onPress={() => this.viewPagerItemClick()}>
                        <Image source={{uri:this.state.images[0]}}
                               style={{height: 245,width}}
                        />
                    </TouchableOpacity>}

            </View>

        )
    }

    collect() {
        if (Global.Const.token == '') {
            // Toast.show('请先登录！');
            this.props.navigator.push({
                id: 'RegisteredContainer',
                component: RegisteredContainer,
                passProps: {},
            });
            return;
        }
        RuralLibraryAPIService.people_collection(Global.Const.token, Global.Const.registeredId, this.props.ID).then((ret)=> {
            if (this.state.is_collect == '0') {
                this.setState({
                    is_collect: '1',
                });
            } else {
                this.setState({
                    is_collect: '0',
                });
            }
        }).catch((err)=> {

        });
    }

    _renderStickyHeader() {
        let collectImg = this.state.is_collect == '1' ?
            require('../../Image/collect_icon.png')
            : require('../../Image/un_collect_icon.png');
        return (
            <View>
                <View style={{height: 55,paddingTop: 15,alignItems: 'center',justifyContent: 'center'}}>
                    <Text style={{color: "#333",fontSize: 18}}>{this.state.SpecialtyDetails.title}</Text>
                </View>
                <View style={{
                    backgroundColor: 'white',
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    paddingRight: 15,
                    paddingLeft: 15,
                    marginTop: 5
                }}>
                    <Text numberOfLines={1} style={{
                        fontSize: 16,
                        marginRight: 10,
                        textAlignVertical: 'center',
                        color: '#333'
                    }}>{this.state.SpecialtyDetails.title}</Text>
                    {_renderStar(this.state.SpecialtyDetails.star, {marginTop: 0})}
                    <View style={{flexDirection:'row',alignItems:'center',justifyContent:'center'}}>
                        <TouchableOpacity onPress={()=>{this.collect()}}>
                            <Image style={{marginRight:10,width:18,height:18,resizeMode:'contain'}}
                                   source={collectImg}
                            ></Image>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.btnBox} onPress={() => {this.goToHelpBuyPage()}}>
                            <Text style={styles.button}>帮购</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        )
    }


    render() {
        let collectImg = this.state.is_collect == '1' ?
            require('../../Image/collect_icon.png')
            : require('../../Image/un_collect_icon.png');
        let object = this.state.SpecialtyDetails;
        let content = this.state.visible ?
            <View style={{flex:1,backgroundColor:'#F5F5F5'}}><View
                style={{position: 'absolute',top:0,left:0,width:Global.Const.size.width,height:Global.Const.size.height,backgroundColor:null,alignItems:'center',justifyContent:'center'}}>
                <View
                    style={{backgroundColor:'#333333',borderRadius:5, alignItems: 'center',justifyContent: 'center',width:80,height:80}}>
                    <ActivityIndicator
                        animating={this.state.animating}
                        style={{ alignItems: 'center',justifyContent: 'center'}}
                        size="large"/>
                    <Text style={{color:'white'}}>加载中...</Text>
                </View>
            </View>
            </View>
            : <ParallaxScrollView
            showsVerticalScrollIndicator={false}
            contentBackgroundColor={'white'}
            backgroundColor={'white'}
            headerBackgroundColor="#333"
            stickyHeaderHeight={ 95 }
            parallaxHeaderHeight={ 245 }
            backgroundSpeed={10}
            renderForeground={() => {
                return (
                    <Foreground
                        height={245}
                        size={this.state.dataSource.getPageCount()}
                        renderHeader={() => this._renderViewPager()}
                    />
                )
            }}
            renderFixedHeader={()=> {
                return (
                    <FixedHeader rightFunc={()=> {
                        this.shareView && this.shareView.showShareView();
                    }} navigator={this.props.navigator}/>
                )
            }}
            renderStickyHeader={()=> this._renderStickyHeader()}
        >
            <View style={styles.flexRow}>
                <View style={{
                    flex: 1
                }}>
                    <Text numberOfLines={1} style={{fontSize: 16,color: '#333'}}>{object.title}</Text>
                    {_renderStar(object.star, null)}
                </View>
                <View style={{flexDirection:'row',alignItems:'center',justifyContent:'center'}}>
                    <TouchableOpacity onPress={()=>{this.collect()}}>
                        <Image style={{marginRight:10,width:18,height:18,resizeMode:'contain'}}
                               source={collectImg}
                        ></Image>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.btnBox} onPress={()=>this.goToHelpBuyPage()}>
                        <Text style={styles.button}>帮购</Text>
                    </TouchableOpacity>
                </View>
            </View>
            <TouchableOpacity onPress={() => this.goToSellPage()}>
                <View style={[
                    {
                        flexDirection: 'row',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        padding: 15,
                        flex: 1,
                    }, styles.tenBorderLine
                ]}>
                    <Text numberOfLines={1}
                          style={{fontSize: 16,color: '#333',flex: 1}}
                    >{object.restaurant}</Text>
                    <Image
                        style={{width: 20,height: 20}}
                        source={require('../../Image/arrow.png')}/>
                </View>
            </TouchableOpacity>
            <WatchMapView navigator={this.props.navigator} {...object} type={1}/>
            <IntroduceView introText={object.content}/>
            <CommentStarView star={object.star.length} commentList={this.state.commentList}
                             id={this.props.ID} type={2}
                             navigator={this.props.navigator}/>
            {this.state.nearFoods ? <View style={styles.borderStyles}>
                <View style={styles.somethingStyle}>
                    <Image style={{width: 15,height: 15,marginRight: 10,resizeMode: 'contain'}}
                           source={require('../../Image/icon_booking.png')}
                    />
                    <Text style={{color: '#333', fontSize: 16}}>附近美食</Text>
                </View>
                <View style={{padding: 10, flexDirection: 'row'}}>
                    {
                        this.state.nearFoods ?
                            this.state.nearFoods.map((item, index) => {
                                return (
                                    <SomethingItemView
                                        key={"foods" + index}
                                        item={item}
                                        navigator={this.props.navigator}
                                        component={SpecialtyDetailsPage}
                                        name="SpecialtyDetailsPage"
                                    />
                                )
                            }) : null
                    }
                </View>
            </View> : null}
        </ParallaxScrollView>;
        return (
            <Animated.View style={{flex: 1, paddingBottom: this.state.paddingBottom,}}>
                {content}
                <BottomShareView
                    shareTitle={ this.state.SpecialtyDetails.title}
                    shareContent={this.state.SpecialtyDetails.content}
                    shareImageUrl={this.state.images[0]}
                    shareUrl={'http://xc.xiarikui.cn/Api/Index/share'}
                    ref={(ref) => {this.shareView = ref;}}/>
                <BottomCommentBtn navigator={this.props.navigator}
                                  type={2}
                                  rid={this.props.ID}
                                  phone={this.state.phone}
                                  refreshComments={()=>this.refreshComments()}
                />
            </Animated.View>
        )
    }
}

export default SpecialtyDetailsPage;